<?php
	require '../../include/library.inc.php';
	require '../../include/admin_login.inc.php';
	
	

	

if (!isset($_POST['is_submitted'])) {
	$_POST['is_submitted'] = '';
}
if (!isset($error_message)) {
	$error_message = '';
}	


if($_POST["redirect"] || $_SESSION['redirect'] ){
	if($_POST["redirect"]) $redirect = $_POST["redirect"];
	if($_SESSION['redirect']){ 
	$redirect = $_SESSION['redirect'];
	unset($_SESSION['redirect']);
	}
}else{
       $redirect = $_SERVER['HTTP_REFERER'];	
     }	
	 	
	if ($_POST['is_submitted']) {
		$error_message = '';
		$redirect = $_POST["redirect"];
    
	
	
	if (!$_POST['title'])  $error_message .= 'Не е въведено заглавие!<br/>';
		
    if(!$error_message) {
		
		
		//Запис на меню
		$sql = "INSERT INTO menus
				  (title,menuitems, published)
				VALUES
				  ('".escape($_POST['title'])."',
				  '".$_POST['output']."',
				  '".intval($_POST['published'])."')";
		query($sql);
		
		$id = mysql_insert_id();
		
		$titles = explode("],",$_POST['titledata']);
		$echo = sizeof($titles);
		  for($u = 0; $u < sizeof($titles)-1; $u++)
		   {   
		   
		   			
		   		$val = explode(",",str_replace('"','',substr($titles[$u],1)));
				
				for($i = 2; $i < sizeof($val);  $i++)
				{
					
				$title = $val[$i];
				$item_id = $val[0];
				$parent_id =$val[1];
				
				$sql = "INSERT INTO menu_description
				  (menu_id,lang_id,item_id,parent_id,title)
				VALUES
				  ('".$id."','".($i-1)."','".$item_id."','".$parent_id."','".$title."')";
				 
		        query($sql);
				}
		   }
		
			
		
		
		
		$_SESSION['message'] .= 'Менюто е създадено успешно!';
         
		redirect(HTML_BASE_ADMIN.'/menu_edit.php?menu_id='.$id);
		   
		
		
    }

}
  	
	
	head_admin("Създаване на ново меню");
	echo $echo;
?>


    

		
            <?php if ($error_message) { ?>
			<div class="message red">
				<h3>Грешка!</h3>
				<?=$error_message?>
			</div>
			<?php } ?>
            
             <?php if ($_SESSION['message']) { ?>
    		<div class="message green">
       			 <?=$_SESSION['message']?>
    		</div>
			<?php unset($_SESSION['message']); } ?>
			
            <div class="topbuttons">
            	<a href="<?=$redirect?>">Обратно</a>
            </div>
			
            <h3>Създаване на ново меню</h3>
			            
            <form id="new_menu" action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_submitted" value="1" />
			<input type="hidden" name="redirect" value="<?=$redirect?>" />
            <input id="redirectForm" type="hidden" name="redirectForm" value="" />
			<input type="hidden" id="output" name="output"/>
			<input type="hidden" id="titledata" name="titledata"/>
			
			<dl>
            <label class="required">Заглавие:</label>
        	<input class="inputbox"   name="title" type="text" value="<?=$_POST['title']?>" >
            
			<input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
			<label>Публикувано</label>
			
			<a style="float:right" class="button" href="#" onClick="senditem(); return false;">запиши</a>
			
           	</dl>
			</form>  
          
          

         <div style="width:30%; float:left;">
         <ul class="type-box">
         	<?php
			
				function get_original_title($id)
				{
					$sql= "SELECT d.title FROM
							page_description AS d
						   WHERE
							d.page_id = '".$id."'
							ORDER BY    d.lang_id
						  ";
						$result = query($sql);
						
						$arr = "";	
						while ($row = mysql_fetch_object($result)) {
							
							$arr .= '|'.$row->title;
						}
						
						return $arr;
				}
				$lang = 1;
				$sql_c = "SELECT
							c.page_id,
							c.order_number,
							c.published,
							
							d.title
							
						FROM
							pages AS c,
							page_description AS d
						WHERE
						
							c.page_id = d.page_id
							
							AND
							
							d.lang_id = '".$lang."'
							
							ORDER BY c.order_number DESC
						  ";
						$result_c = query($sql_c);
							
						while ($row = mysql_fetch_object($result_c)) {
                          ?>
                        <li>
                        <a href="#" onClick="additem(<?=$row->page_id?>,'<?=get_original_title($row->page_id)?>'); return false;"><?=$row->title?> &raquo;</a>
                         
                        </li>
        			<?php  } ?>
				</ul>
         
         </div>
 
  
  
  
  
   
   

    <div class="cf nestable-lists" >

        <div class="dd" id="nestable3" >
            <ol id="cover-item" class="dd-list">
                
            </ol>
        </div>

    </div>
  
  
  
<script src="js/jquery.nestable.js"></script>
<script type="text/javascript">
$(document).ready(function()
{

    var updateOutput = function(e)
    {
        var list   = e.length ? e : $(e.target),
            output = list.data('output');
        if (window.JSON) {
            output.val(window.JSON.stringify(list.nestable('serialize')));//, null, 2));
        } else {
            output.val('JSON browser support required for this demo.');
        }
    };

   

    $('#nestable-menu').on('click', function(e)
    {
        var target = $(e.target),
            action = target.data('action');
        if (action === 'expand-all') {
            $('.dd').nestable('expandAll');
        }
        if (action === 'collapse-all') {
            $('.dd').nestable('collapseAll');
        }
    });

    $('#nestable3').nestable();
	
	
	// activate Nestable for list 2
    $('#nestable3').nestable({
        group: 1
    })
    .on('change', updateOutput);

    // output initial serialised data
    updateOutput($('#nestable3').data('output', $('#output')));
	
	


});


var menuitems = 0;
function additem(itemid,itm)
{
	var titleitm = itm.split("|");
	var title = titleitm[1];
	var tamplate  = '<li class="dd-item dd3-item" data-id="' + menuitems + '" id=\"id-' + menuitems + '">\n <div class="dd-handle dd3-handle"></div><div class=\"dd3-content">'+title+'  </div><div class="act-btns"><a href="#" class="edit" onClick="edititem(' + menuitems +'); return false;">Редактирай</a> <a class="delete" href="#" onClick="deleteitem(' + menuitems +'); return false;">Изтрий</a></div> \n <div class="menu-titles" id="input' + menuitems +'"> \n <input type="hidden"  value="'+itemid+'" />			';
 <?php 
			
			$sql = 'SELECT lang_id,Name,code
					FROM language
					WHERE published';
			$result = query($sql);
			
			
			while ($row_lang = mysql_fetch_object($result)) {
				
			?>
			tamplate += '<label><?=$row_lang->Name?></label> <input class="inputbox w250"  value="'+ titleitm[<?=$row_lang->lang_id?>]+'"/><br/>';
			
			<?php
			 }?>
tamplate += '</div>\n</li>';
	
	
	$('#cover-item').append(tamplate);
	$('#nestable3').change();
	
	menuitems++;
}

function deleteitem(id)
{
	var answer = confirm("Внимание! Ще бъдат изтрити и елеметите свързани с този. Изтриване?")
		if (answer){
			  $('#id-'+id).remove();
			  $('#nestable3').change();
		}
}

function edititem(id)
{
	$('#input'+id).toggle(200);
}

function senditem()
{
	var str = '';
	$( ".dd-item" ).each(function() {
		
		str += '["'+$( this ).attr('data-id');
		var ie = $( this ).attr('data-id');
  		
		$( '#input'+ie+' input').each(function() {
			str += '","'+ $( this ).val();
		});
		str += '"],';
	});
	
	
	$('#titledata').val(str);
	
	$('#new_menu').submit();
}
</script>
            
<?php
	
	foot_admin(); 
?>